package duoxiancheng;

/**
 * 同步方法
 * 同步块，目标更明确
 */
public class synTest02 {
    public static void main(String[] args) {
        //账户
        safaAccount account = new safaAccount(100,"礼金");
        safaDrawing you = new safaDrawing(account,80);
        safaDrawing wife = new safaDrawing(account,90);
        new Thread(you,"a").start();
        new Thread(wife,"b").start();
    }
}

//账户
class safaAccount{
    int money;//金额
    String name;//名称

    public safaAccount(int money, String name) {
        this.money = money;
        this.name = name;
    }
}

//模拟取款
class safaDrawing implements Runnable{
    safaAccount account;//取钱的账户
    int drawMoney;//取的钱数
    int drawTotal;//取得总数
    int packetTotal;//口袋的钱为

    public safaDrawing(safaAccount account, int drawMoney) {
        this.account = account;
        this.drawMoney = drawMoney;
    }

    @Override
    public void run() {
        test();
    }

    public void test(){
        if(account.money<=0){//提高性能的代码
            return;
        }
        synchronized (account){
            if (account.money-drawMoney<0){
                return;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            account.money-=drawMoney;
            packetTotal+=drawMoney;
            System.out.println(Thread.currentThread().getName()+"--->账户余额为："+account.money);
            System.out.println(Thread.currentThread().getName()+"--->口袋的钱为："+packetTotal);
        }
    }
}